/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Vben、ThinkGem
 */
import type { AppRouteRecordRaw, Menu } from '/@/router/types';

import { defineStore } from 'pinia';
import { store } from '/@/store';
import { useI18n } from '/@/hooks/web/useI18n';
import { useUserStore } from './user';
import { useAppStoreWithOut } from './app';
import { toRaw } from 'vue';
import { transformObjToRoute, flatMultiLevelRoutes } from '/@/router/helper/routeHelper';
import { transformRouteToMenu } from '/@/router/helper/menuHelper';

import projectSetting from '/@/settings/projectSetting';

import { PermissionModeEnum } from '/@/enums/appEnum';

import { asyncRoutes } from '/@/router/routes';
import { ERROR_LOG_ROUTE } from '/@/router/routes/basic';

import { filter } from '/@/utils/helper/treeHelper';

import { useMessage } from '/@/hooks/web/useMessage';
import { PageEnum } from '/@/enums/pageEnum';
import { userInfoApi } from '/@/api/tb/login';
import { getCurrentUserMenus } from '/@/api/tb/role';
import { isEmpty } from '/@/utils/is';

interface PermissionState {
  // Whether the route has been dynamically added
  isDynamicAddedRoute: boolean;
  // To trigger a menu update
  lastBuildMenuTime: number;
  // Backstage menu list
  backMenuList: Menu[];
  frontMenuList: Menu[];
  // 可访问的路由名称列表
  accessibleRoutes: string[];
}
export const usePermissionStore = defineStore('app-permission', {
  state: (): PermissionState => ({
    // Whether the route has been dynamically added
    isDynamicAddedRoute: false,
    // To trigger a menu update
    lastBuildMenuTime: 0,
    // Backstage menu list
    backMenuList: [],
    // menu List
    frontMenuList: [],
    // 可访问的路由名称列表
    accessibleRoutes: [],
  }),
  getters: {
    getBackMenuList(): Menu[] {
      return this.backMenuList;
    },
    getFrontMenuList(): Menu[] {
      return this.frontMenuList;
    },
    getLastBuildMenuTime(): number {
      return this.lastBuildMenuTime;
    },
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    },
    getAccessibleRoutes(): string[] {
      return this.accessibleRoutes;
    },
  },
  actions: {
    setBackMenuList(list: Menu[]) {
      this.backMenuList = list;
      list?.length > 0 && this.setLastBuildMenuTime();
    },
    setFrontMenuList(list: Menu[]) {
      this.frontMenuList = list;
    },
    setLastBuildMenuTime() {
      this.lastBuildMenuTime = new Date().getTime();
    },
    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added;
    },
    setAccessibleRoutes(routes: string[]) {
      this.accessibleRoutes = routes;
    },
    resetState(): void {
      this.isDynamicAddedRoute = false;
      this.backMenuList = [];
      this.lastBuildMenuTime = 0;
      this.accessibleRoutes = [];
    },
    async changePermissionCode() {
      const userStore = useUserStore();
      const authInfo = await userInfoApi();
      userStore.setAuthority(authInfo?.authority);
    },
    async buildRoutesAction(): Promise<AppRouteRecordRaw[]> {
      const { t } = useI18n();
      const userStore = useUserStore();
      const appStore = useAppStoreWithOut();
      const { createMessage } = useMessage();

      let routes: AppRouteRecordRaw[] = [];
      const currentAuthority = toRaw(userStore.getAuthority);
      const { permissionMode = projectSetting.permissionMode } = appStore.getProjectConfig;

      // 获取当前用户可访问的路由列表
      try {
        const accessibleRoutes = await getCurrentUserMenus();
        this.setAccessibleRoutes(accessibleRoutes);
        console.log('获取到可访问路由列表:', accessibleRoutes);
      } catch (error) {
        console.error('获取菜单权限失败:', error);
        createMessage.error('获取菜单权限失败，请刷新页面重试');
        throw error; // 抛出错误，阻止继续加载
      }

      // 基于路由名称的过滤器
      const routeNameFilter = (route: AppRouteRecordRaw) => {
        const accessibleRoutes = this.getAccessibleRoutes;
        // 如果包含 "ALL"，则表示拥有所有权限
        if (accessibleRoutes.includes('ALL')) {
          return true;
        }

        // 如果路由本身在权限列表中,保留
        if (route.name && accessibleRoutes.includes(route.name as string)) {
          return true;
        }

        // 如果路由有子路由,检查是否有任何子路由在权限列表中
        // 如果有,则保留父路由
        if (route.children && route.children.length > 0) {
          const hasAccessibleChild = route.children.some((child) => {
            if (!child.name) return false;
            return accessibleRoutes.includes(child.name as string);
          });
          if (hasAccessibleChild) {
            return true;
          }
        }

        return false;
      };

      // 保留旧的 authority 过滤器作为备用（暂时保留，后续可删除）
      const routeFilter = (route: AppRouteRecordRaw) => {
        const { meta } = route;
        const { authority: authorityList } = meta || {};
        if (!authorityList || isEmpty(authorityList)) return true;

        return (authorityList as any[]).includes(currentAuthority) || (authorityList as any[]).includes('*');
      };

      const routeRemoveIgnoreFilter = (route: AppRouteRecordRaw) => {
        const { meta } = route;
        const { ignoreRoute } = meta || {};
        return !ignoreRoute;
      };

      /**
       * @description 根据设置的首页path，修正routes中的affix标记（固定首页）
       * */
      const patchHomeAffix = (routes: AppRouteRecordRaw[]) => {
        if (!routes || routes.length === 0) return;
        let homePath: string = userStore.getUserInfo.additionalInfo?.homePath || PageEnum.BASE_HOME;
        function patcher(routes: AppRouteRecordRaw[], parentPath = '') {
          if (parentPath) parentPath = parentPath + '/';
          routes.forEach((route: AppRouteRecordRaw) => {
            const { path, children, redirect } = route;
            const currentPath = path.startsWith('/') ? path : parentPath + path;
            if (currentPath === homePath) {
              if (redirect) {
                homePath = route.redirect! as string;
              } else {
                route.meta = Object.assign({}, route.meta, { affix: true });
                throw new Error('end');
              }
            }
            children && children.length > 0 && patcher(children, currentPath);
          });
        }
        try {
          patcher(routes);
        } catch (e) {
          // 已处理完毕跳出循环
        }
        return;
      };

      switch (permissionMode) {
        case PermissionModeEnum.ROLE:
          routes = filter(asyncRoutes, routeFilter);
          routes = routes.filter(routeFilter);
          // Convert multi-level routing to level 2 routing
          routes = flatMultiLevelRoutes(routes);
          break;

        case PermissionModeEnum.ROUTE_MAPPING:
          // 使用新的基于路由名称的过滤逻辑
          routes = filter(asyncRoutes, routeNameFilter);
          routes = routes.filter(routeNameFilter);
          const menuList = transformRouteToMenu(routes, true);
          routes = filter(routes, routeRemoveIgnoreFilter);
          routes = routes.filter(routeRemoveIgnoreFilter);
          menuList.sort((a, b) => {
            return (a.meta?.orderNo || 0) - (b.meta?.orderNo || 0);
          });

          this.setFrontMenuList(menuList);
          // Convert multi-level routing to level 2 routing
          routes = flatMultiLevelRoutes(routes);
          break;

        //  If you are sure that you do not need to do background dynamic permissions, please comment the entire judgment below
        case PermissionModeEnum.BACK:
          createMessage.loading({
            content: t('sys.app.menuLoading'),
            duration: 1,
          });

          // !Simulate to obtain permission codes from the background,
          // this function may only need to be executed once, and the actual project can be put at the right time by itself
          let routeList: AppRouteRecordRaw[] = [];
          try {
            this.changePermissionCode();
            // routeList = (await menuRouteApi()) as AppRouteRecordRaw[];
            routeList = [];
          } catch (error) {
            console.error(error);
          }

          // Dynamically introduce components
          routeList = transformObjToRoute(routeList);

          //  Background routing to menu structure
          const backMenuList = transformRouteToMenu(routeList);
          this.setBackMenuList(backMenuList);

          // remove meta.ignoreRoute item
          // routeList = filter(routeList, routeRemoveIgnoreFilter);
          // routeList = routeList.filter(routeRemoveIgnoreFilter);

          routeList = flatMultiLevelRoutes(routeList);
          routes = [...asyncRoutes, ...routeList];
          break;
      }

      routes.push(ERROR_LOG_ROUTE);
      patchHomeAffix(routes);
      return routes;
    },
  },
});

// Need to be used outside the setup
export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
